<?php


namespace App\Services\Game;


use App\DTOS\Admin\PayOrderDTO;
use App\DTOS\Admin\PayOrderInsertDTO;
use App\Exceptions\ServiceException;
use App\Models\Customer;
use App\Models\Game\GameGoods;
use App\Models\Game\GamePackage;
use App\Models\Game\PayOrder;
use App\Models\Game\PayOrderTop;
use App\Models\Game\Server;
use App\Models\Game\ServerGroup;
use App\Utils\MyLog;


class PayOrderService
{

    private NeigouService $NeigouService;

    /**
     * PayOrderService constructor.
     * @param NeigouService $NeigouService
     */
    public function __construct(NeigouService $NeigouService)
    {
        $this->NeigouService = $NeigouService;
    }

    public function paginate(PayOrderDTO $DTO){
        $model = PayOrder::query();
        $limit = $DTO->getLimit();
        $page = $DTO->getPage();
        $gameArea = $DTO->getGameArea();
        $gameAreas = $DTO->getGameAreas();
        $channel = $DTO->getChannel();
        $roleId = $DTO->getRoleId();
        $status = $DTO->getStatus();
        $pushStatus = $DTO->getPushStatus();
        $orderNo = $DTO->getOrderNo();
        $channelOrderNo = $DTO->getChannelOrderNo();
        $customerId = $DTO->getCustomerId();
        $customerIds = $DTO->getCustomerIds();
        $gameGoods = $DTO->getGameGoods();
        $createDateTimeBegin = $DTO->getCreateDateTimeBegin();
        $createDateTimeEnd = $DTO->getCreateDateTimeEnd();
        $packageNos=$DTO->getPackeageNo();
        if($packageNos){
            $model->whereIn("package_no",$packageNos);
        }
        if ($createDateTimeBegin){
            $model->where("created_at",">=",$createDateTimeBegin);
        }
        if ($createDateTimeEnd){
            $model->where("created_at","<=",$createDateTimeEnd);
        }
        if ($gameArea!==null) {
            $model->where('game_area',$gameArea);
        }
        if ($gameAreas!==null) {
            $model->whereIn('game_area',$gameAreas);
        }
        if ($channel!==null){
            $model->whereRaw("SUBSTRING_INDEX(order_no,'_',1) = ?",[$channel]);
        }
        if ($roleId) {
            $model->where('role_id',$roleId);
        }
        if ($status!==null) {
            $model->where('status',(int)$status);
        }
        if ($pushStatus!==null){
            $model->where('push_status',(int)$pushStatus);
        }
        if ($orderNo) {
            $model->where('order_no',$orderNo);
        }
        if ($channelOrderNo){
            $model->where('channel_order_no',$channelOrderNo);
        }
        if ($customerId){
            $model->where('customer_id',$customerId);
        }
        if (!empty($customerIds)){
            $model->whereIn('customer_id',$customerIds);
        }
        if (!empty($gameGoods)){
            $gameGoodsArray = explode(',', $gameGoods);

            $model->whereIn('goods_id',$gameGoodsArray);
        }
        return $model->orderByDesc('id')->paginate($limit,'*','page',$page);
    }

    /**
     * @param PayOrderInsertDTO $DTO
     * @return bool
     * @throws ServiceException
     */
    public function createOrder(PayOrderInsertDTO $DTO)
    {
        //判断白名单
        $customerId = $DTO->getCustomerId();
        $serverId = $DTO->getGameArea();
        $server = Server::query()->where('server_id',$serverId)->first();
        if ($server->pay_status==0){
            throw new ServiceException('充值功能已经关闭');
        }
        $customer = Customer::query()->find($customerId);
        if (!$customer){
            throw new ServiceException("用户不存在");
        }
        PayOrder::query()->insert([
            'order_no'=>$DTO->getOrderNo(),
            'name'=>$DTO->getName(),
            'detail'=>$DTO->getDetail(),
            'status'=>0,
            'game_area'=>$serverId,
            'front_fee'=>$DTO->getFrontFee(),
            'fee'=>$DTO->getFee(),
            'customer_id'=>$customerId,
            'role_id'=>$DTO->getRoleId(),
            'goods_id'=>$DTO->getGoodsId(),
            'number'=>$DTO->getNumber(),
            'created_at'=>date("Y-m-d H:i:s"),
        ]);
        return true;
    }


    public function topPaginate(PayOrderDTO $DTO){
        $model = PayOrderTop::query();
        $limit = $DTO->getLimit();
        $page = $DTO->getPage();
        $gameArea = $DTO->getGameArea();
        $gameAreas = $DTO->getGameAreas();
        $channel = $DTO->getChannel();
        $roleId = $DTO->getRoleId();
        $status = $DTO->getStatus();
        $pushStatus = $DTO->getPushStatus();
        $orderNo = $DTO->getOrderNo();
        $channelOrderNo = $DTO->getChannelOrderNo();
        $customerId = $DTO->getCustomerId();
        $customerIds = $DTO->getCustomerIds();
        $gameGoods = $DTO->getGameGoods();
        $createDateTimeBegin = $DTO->getCreateDateTimeBegin();
        $createDateTimeEnd = $DTO->getCreateDateTimeEnd();
        $packageNos=$DTO->getPackeageNo();
        if($packageNos){
            $model->whereIn("package_no",$packageNos);
        }
        if ($createDateTimeBegin){
            $model->where("created_at",">=",$createDateTimeBegin);
        }
        if ($createDateTimeEnd){
            $model->where("created_at","<=",$createDateTimeEnd);
        }
        if ($gameArea!==null) {
            $model->where('game_area',$gameArea);
        }
        if ($gameAreas!==null) {
            $model->whereIn('game_area',$gameAreas);
        }

        if ($roleId) {
            $model->where('role_id',$roleId);
        }
        if ($status!==null) {
            $model->where('status',(int)$status);
        }


        if ($customerId){
            $model->where('customer_id',$customerId);
        }
        if (!empty($customerIds)){
            $model->whereIn('customer_id',$customerIds);
        }

        return $model->orderBy('sumfee', 'desc')->paginate($limit, '*', 'page', $page);
    }




    public function ordersPaginate(PayOrderDTO $DTO){
        $model = PayOrder::query();
        $limit = $DTO->getLimit();
        $page = $DTO->getPage();
        $gameArea = $DTO->getGameArea();
        $gameAreas = $DTO->getGameAreas();
        $channel = $DTO->getChannel();
        $roleId = $DTO->getRoleId();
        $status = $DTO->getStatus();
        $pushStatus = $DTO->getPushStatus();
        $orderNo = $DTO->getOrderNo();
        $channelOrderNo = $DTO->getChannelOrderNo();
        $customerId = $DTO->getCustomerId();
        $customerIds = $DTO->getCustomerIds();
        $gameGoods = $DTO->getGameGoods();
        $createDateTimeBegin = $DTO->getCreateDateTimeBegin();
        $createDateTimeEnd = $DTO->getCreateDateTimeEnd();
        $packageNos=$DTO->getPackeageNo();

        if ($gameGoods){
            $model->where("goods_id",$gameGoods);
        }

        if ($createDateTimeBegin){
            $model->where("created_at",">=",$createDateTimeBegin);
        }
        if ($createDateTimeEnd){
            $model->where("created_at","<=",$createDateTimeEnd);
        }
        if ($gameArea!==null) {
            $model->where('game_area',$gameArea);
        }
        if ($gameAreas!==null) {
            $model->whereIn('game_area',$gameAreas);
        }

        if ($status!==null) {
            $model->where('status',(int)$status);
        }

        // 实现分组和计数
        $results = $model
            ->selectRaw(' goods_id, game_area, fee,COUNT(*) AS order_count, SUM(fee) AS total_fee')
            ->groupBy( 'goods_id', 'game_area','fee')
            ->orderByRaw('COUNT(*) DESC') // 使用 COUNT(*) 进行排序
            ->get();

        // 计算总金额和总订单数量
        $totalFee = $results->sum('total_fee');
        $totalOrdersCount = $results->sum('order_count');

        // 统计每个商品的占比和成功/未成功支付的订单数量
        foreach ($results as $result) {
            // 计算金额占比
            $result->fee_percentage = $totalFee > 0 ? number_format(($result->total_fee / $totalFee) * 100, 2) : 0;

            // 计算订单数量占比
            $result->order_percentage = $totalOrdersCount > 0 ? number_format(($result->order_count / $totalOrdersCount) * 100, 2) : 0;

            if ($createDateTimeBegin){
                $model->where("created_at",">=",$createDateTimeBegin);
            }
            if ($createDateTimeEnd){
                $model->where("created_at","<=",$createDateTimeEnd);
            }

            // 统计该商品在该区域的支付成功和未支付订单数量
            // 统计该商品在该区域的支付成功和未支付订单数量
            $successfulOrdersCount = PayOrder::query()
                ->where('goods_id', $result->goods_id)
                ->where('game_area', $result->game_area)
                ->where('status', 1) // 假设 1 表示支付成功
                ->when($createDateTimeBegin, function ($query) use ($createDateTimeBegin) {
                    return $query->where('created_at', '>=', $createDateTimeBegin);
                })
                ->when($createDateTimeEnd, function ($query) use ($createDateTimeEnd) {
                    return $query->where('created_at', '<=', $createDateTimeEnd);
                })
                ->count();
            //支付成功总金额
            $successfulOrderstotalfee = PayOrder::query()
                ->where('goods_id', $result->goods_id)
                ->where('game_area', $result->game_area)
                ->where('status', 1) // 假设 1 表示支付成功
                ->when($createDateTimeBegin, function ($query) use ($createDateTimeBegin) {
                    return $query->where('created_at', '>=', $createDateTimeBegin);
                })
                ->when($createDateTimeEnd, function ($query) use ($createDateTimeEnd) {
                    return $query->where('created_at', '<=', $createDateTimeEnd);
                })->sum('fee');

            $unsuccessfulOrdersCount = PayOrder::query()
                ->where('goods_id', $result->goods_id)
                ->where('game_area', $result->game_area)
                ->where('status', '!=', 1) // 其他状态表示未支付成功
                ->when($createDateTimeBegin, function ($query) use ($createDateTimeBegin) {
                    return $query->where('created_at', '>=', $createDateTimeBegin);
                })
                ->when($createDateTimeEnd, function ($query) use ($createDateTimeEnd) {
                    return $query->where('created_at', '<=', $createDateTimeEnd);
                })
                ->count();

            // 将结果添加到当前商品的统计中
            $result->successful_orders_count = $successfulOrdersCount;
            $result->unsuccessful_orders_count = $unsuccessfulOrdersCount;
            $result->successfulOrderstotalfee = $successfulOrderstotalfee;

        }

        // 返回结果
        return $results;
    }


    //根据包含查询
    //根据包含查询
    public function findConfigIndex( $packageNo,$goodsId)
    {

        $GamePackage=GamePackage::query()->where('package_no',$packageNo)->first();

        if ($GamePackage && $GamePackage->configtype) {
            // 获取 type 字段值
            MyLog::info('分组信息'.json_encode($GamePackage));

            $type=$GamePackage->configtype;
            $gameGoods = GameGoods::query()->where('channeltype', $type)->find($goodsId);
            // 你可以在这里使用 $type 值
        } else {
            // 处理 ServerGroup 不存在的情况
            // 例如：返回错误信息或设置默认值
            $gameGoods = GameGoods::query()->where('channeltype', 0)->find($goodsId);
        }
        MyLog::info('商品信息'.json_encode($gameGoods));
        return $gameGoods;
    }

}
